import { Tabs } from 'antd-mobile'
import styles from './index.module.scss'
import { useAppDispatch, getUserChannel, useAppSelector, setActiveChannel } from '@/store/index'
import { useInitialState } from '@/hooks/useInitialState'
import Icon from '@/components/icon/index'
import { useState } from 'react'
import { Popup } from 'antd-mobile'
import Channels from './components/Channels'
import ArticleList from './components/ArticleList'
import { useNavigate } from 'react-router-dom'

export default function Home() {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  // 频道信息数据
  const { channels } = useInitialState(getUserChannel, 'homeSlice')
  // 频道高亮key
  const { activeChannel } = useAppSelector((state) => state.homeSlice)

  // 面板切换事件
  function onTabChange(e: string) {
    dispatch(setActiveChannel(parseFloat(e)))
  }

  // 频道管理弹框
  const [visible, setVisible] = useState(false)
  // 显示频道
  function show() {
    setVisible(true)
  }
  // 隐藏频道
  function hide() {
    setVisible(false)
  }
  return (
    <>
      <div className={styles.root}>
        {/* 频道 Tabs 列表 */}
        <Tabs className="tabs" activeKey={activeChannel.toString()} onChange={onTabChange}>
          {channels.map((item) => (
            <Tabs.Tab title={item.name} key={item.id}>
              <ArticleList channelId={item.id}></ArticleList>
            </Tabs.Tab>
          ))}
        </Tabs>
        <div className="tabs-opration">
          <Icon type="iconbtn_search" onClick={() => navigate('/search')} />
          <Icon type="iconbtn_channel" onClick={show} />
        </div>
      </div>

      <Popup position="left" visible={visible}>
        <Channels hide={hide}></Channels>
      </Popup>
    </>
  )
}
